<template>
<div class="bscroll_wrappper wrapper" ref="wrapper">
  <div :style="{width: wWidth}" class="test" ref="scrollInner">
    <!-- 下拉刷新 部分-->
    <div class="pullDownDiv" v-if="pulldown">
      <label>{{ pullDownText }}</label><span>{{ currentTime }}</span>
    </div>
    <!-- 滚动内容 部分 -->
    <van-loading type="spinner" v-show="currPage === 1 && loading" class="tc" size="20px">加载中...</van-loading>
    <slot>
      <!-- <div class="no-data">----暂无数据----</div> -->
      <!--默认无数据样式-->
      <no-data v-show="!noDataText && currPage === 1 && !loading && !data.length"></no-data>
      <!--自定义无数据文案-->
      <div v-show="noDataText" class="no-data">{{noDataText}}</div>
    </slot>
    <!-- 上拉加载 部分 -->
    <div class="pullUpDiv" ref="pullUpDiv">
      <label v-if="checkPullUp">{{ pullUpText }}<span>{{ currentTime }}</span></label>
      <label v-else-if="data.length>0">----{{ NoMoreText }}----</label>
      <!-- pullUp部分修饰 -->
      <slot name="pullUp"></slot>
    </div>

    <slot name="footer" v-if="(!loading && currPage === 1) || (currPage !== 1)"></slot>

  </div>
</div>
</template>
<script>
import { Loading } from 'vant';
import BScroll from 'better-scroll';
import DZUtils from '@/utils/DZUtils.js';
import NoData from '@/components/common/noData.vue';

export default {
  components: {
    [Loading.name]: Loading,
    NoData
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    noDataText: {
      type: String,
      default: ''
    },
    /**
    * 1 滚动的时候会派发scroll事件，会截流。
    * 2 滚动的时候实时派发scroll事件，不会截流。
    * 3 除了实时派发scroll事件，在swipe的情况下仍然能实时派发scroll事件
    */
    probeType: {
      type: Number,
      default: 1
    },
    /** * 点击列表是否派发click事件 */
    click: {
      type: Boolean,
      default: true
    },
    /** * 是否开启横向滚动 */
    scrollX: {
      type: Boolean,
      default: false
    },
    /** * 是否派发滚动事件 */
    listenScroll: {
      type: Boolean,
      default: true
    },
    /** * 是否开启动量 */
    id: {
      type: String,
      default: ''
    },
    momentum: {
      type: Boolean,
      default: true
    },
    bounce: {
      type: Boolean,
      default: true
    },
    bounceTime: {
      type: Number,
      default: 700
    },
    /** * 列表的数据 */
    data: {
      type: Array,
      default: null
    },
    /** * 列表的数据 */
    totalPage: {
      type: Number,
      default: 0
    },
    // 针对订单列表页
    day: {
      type: String,
      default: ''
    },
    /** * 数据刷新 */
    refreshTime: {
      type: Number,
      default: 0
    },
    /** * 是否派发滚动到底部的事件，用于上拉加载 */
    pullup: {
      type: Boolean,
      default: false
    },
    /** * 是否派发顶部下拉的事件，用于下拉刷新 */
    pulldown: {
      type: Boolean,
      default: false
    },
    /** * 处理特殊情况，下拉时取消滚动效果 */
    pulldownDisable: {
      type: Boolean,
      default: false
    },
    /** * 是否派发列表滚动开始的事件 */
    beforeScroll: {
      type: Boolean,
      default: false
    },
    /** * 当数据更新后，刷新scroll的延时。 */
    refreshDelay: {
      type: Number,
      default: 20
    },
    busCurrPage: {
      type: Number,
    }
  },
  data() {
    return {
      pullDownText: '下拉刷新',
      pullUpText: '上拉加载更多',
      currentTime: this.getCurrentTime('HHmmss'),
      currPage: 1,
      wWidth: 'intial',
    };
  },
  computed: {
    checkPullUp() {
      // console.log('_________this.totalPage', this.totalPage);
      return this.pullup && this.totalPage > 1;
    },
    NoMoreText() {
      return this.day ? `以上为最近${this.day}订单` : '数据已经加载完了';
    },
  },
  mounted() {
    // 保证在DOM渲染完毕后初始化better-scroll
    this.$nextTick(() => {
      this.initScroll();
      if (this.scrollX) {
        this.wWidth = `${this.$refs.wrapper.childNodes[0].querySelector(`#${this.id}`).clientWidth}px`;
      }
    });
  },
  methods: {
    initScroll() {
      if (!this.$refs.wrapper) {
        return;
      }
      // better-scroll的初始化
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        scrollX: this.scrollX,
        momentum: this.momentum,
        bounce: this.bounce,
        bounceTime: this.bounceTime
      });
      window.scroller = this.scroll;
      this.$emit('bscroll-init');
      // 是否派发滚动事件
      if (this.listenScroll) {
        const __this = this;
        this.scroll.on('scroll', (pos) => {
          __this.$emit('scroll', pos);
          if (pos.y > 50 || pos.y < this.scroll.maxScrollY) {
            __this.pullUpText = __this.pullDownText = '释放刷新';
          }

          if (pos.y < 0 && pos.y > this.scroll.maxScrollY) {
            __this.pullUpText = '上拉加载更多';
          }
          if (pos.y > 0 && pos.y < 50) {
            __this.pullDownText = '下拉刷新';
          }
        });
        this.scroll.on('scrollEnd', (pos) => {
          __this.$emit('scroll', pos);
        });
      }
      // 是否派发滚动到底部事件pullup，用于上拉加载
      if (this.pullup) {
        const __this = this;
        this.scroll.on('touchEnd', (pos) => {
          // console.log(pos.y,__this.scroll.maxScrollY);

          // 滚动到底部
          if (pos.y < __this.scroll.maxScrollY) {
            __this.pullUpText = '加载中......';
            __this.currentTime = __this.getCurrentTime('HHmmss');
            setTimeout(() => {
              // console.log(__this.currPage, __this.totalPage);
              if (__this.currPage === __this.totalPage) {
                if (__this.day) {
                  __this.pullUpText = `以上为最近${__this.day}订单`;
                } else {
                  __this.pullUpText = '数据已经加载完了';
                }
              } else {
                if (__this.day && __this.totalPage > 1 && __this.totalPage - 1 === __this.currPage) {
                  __this.pullUpText = `以上为最近${__this.day}订单`;
                } else {
                  __this.pullUpText = '上拉加载更多';
                }
                __this.currPage++;
                __this.$emit('pullup');
              }
            }, 500);
          }
        });
      }
      // 是否派发顶部下拉事件pulldown，用于下拉刷新
      if (this.pulldown) {
        const __this = this;
        this.scroll.on('touchEnd', (pos) => {
          // 滚动到底部
          if (pos.y > 50) {
            __this.pullDownText = '加载中......';
            this.currentTime = __this.getCurrentTime('HHmmss');
            setTimeout(() => {
              __this.$emit('pulldown');
              __this.pullDownText = '下拉刷新';
            }, 500);
          }
        });
      } else if (this.pulldownDisable) {
        const _ = this;
        this.scroll.on('touchEnd', (pos) => {
          // 滚动到底部
          if (pos.y >= 0) {
            _.scroll.disable();
          }
        });
      }
      // 是否派发列表滚动开始的事件
      if (this.beforeScroll) {
        this.scroll.on('beforeScrollStart', () => {
          this.$emit('beforeScroll');
        });
      }
    },
    disable() {
      // 代理better-scroll的disable方法
      this.scroll && this.scroll.disable();
    },
    enable() {
      // 代理better-scroll的enable方法
      this.scroll && this.scroll.enable();
    },
    refresh() {
      // 代理better-scroll的refresh方法
      this.scroll && this.scroll.refresh();
    },
    scrollTo() {
      // 代理better-scroll的scrollTo方法
      this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments);
    },
    scrollToElement() {
      // 代理better-scroll的scrollToElement方法
      this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments);
    },
    prefixInteger(num, length) {
      return (Array(length).join('0') + num).slice(-length);
    },
    getCurrentTime(fmat, date) {
      const t = date ? new Date(date) : new Date();
      let h; let min; let s;

      h = this.prefixInteger(t.getHours(), 2);
      min = this.prefixInteger(t.getMinutes(), 2);
      s = this.prefixInteger(t.getSeconds(), 2);

      /* 格式00:00:00 */
      if (fmat === 'HHmmss') {
        return `${h}:${min}:${s}`;
      }
    },
  },
  watch: {
    // 监听数据的变化，延时refreshDelay时间后调用refresh方法重新计算，保证滚动效果正常
    data(val) {
      if (typeof this.busCurrPage === 'number' && this.busCurrPage === 0) {
        this.currPage = 1;
      }
      setTimeout(() => {
        this.refresh();
      }, this.refreshDelay);
    },
    refreshTime() {
      this.currPage = 1;
      this.pullUpText = '上拉加载更多';
    },
  },
  destroyed() {
    this.scroll = null;
  }
};
</script>
<style lang="less" scoped>
.wrapper{
  height: 100%;
  overflow: hidden;
  .test{
    min-height: 100px;
  }
  .pullDownDiv,
  .pullUpDiv,
  .no-data{
    line-height: 30px;
    padding: 8px 0;
    font-size: 13px;
    color: #999;
    text-align: center;
  }
  .pullDownDiv{
    margin-top: -50px;
  }
}
</style>
